package com.wang.springbootinit.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadPoolExecutorConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        ThreadFactory threadFactory = new ThreadFactory() {
            private int count = 1;

            @Override
            public Thread newThread(@NotNull Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("线程_" + count++);
                return thread;
            }
        };

        /**
         * corePoolSize 核心线程数 同时可以执行的线程数
         * maximumPoolSize 最大线程数，当任务队列满时，就由超出核心线程数并且小于最大线程数的线程去执行任务队列之外的任务
         * keepAliveTime 空闲队列空闲时间
         * TimeUnit 空闲时间的单位 s
         * BlockingQueue<Runnable> workQueue, 任务队列（阻塞队列） 阻塞队列中可以等待的队列数
         * ThreadFactory threadFactory 线程工厂，控制每个线程的生成，线程的属性等 比如线程名等
         * RejectedExecutionHandler 队列拒绝策略 线程池拒绝策略  任务队列满时 我们采取什么措施。比如抛异常，不跑异常 自定义策略等。
         */
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 8, 100, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100), threadFactory);
        return threadPoolExecutor;
    }
}
